package cn.amossun.starter.mybatis.data.security.interceptor;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import cn.amossun.starter.mybatis.data.security.rewrite.DecryptPreParameterRewriter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.sql.Statement;

/**
 * @description: 除存储过程及返回值类型为Cursor以外的查询方法中被调用，对于拦截处理查询结果非常有用(被调用的位置在处理二级缓存之前)
 * @author: Amos.Sun
 * @DateTime: 2020/03/08 15:23
 **/
@Slf4j
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)
})
@AllArgsConstructor
public class ResultSetHandlerInterceptor implements Interceptor {

    private final DecryptPreParameterRewriter decryptRewriter;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object target = PluginUtils.realTarget(invocation.getTarget());
        if(!(target instanceof DefaultResultSetHandler)){
            return invocation.proceed();
        }
        Object result = invocation.proceed();
        decryptRewriter.rewrite(result);
        return result;
    }


}
